﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Logging;
using WuDada.Core.Post;
using WuDada.Core.Post.Domain;
using WuDada.Core.Post.Service;
using WuDada.Core.SystemApplications.Domain;
using System.Collections;
using System.Collections.Generic;

public partial class admin_UC08_0821 : System.Web.UI.Page
{
    private ILog m_Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private PostFactory m_PostFactory;
    private IPostService m_PostService;
    private IQuestionService m_QuestionService;
    private WebLogService m_WebLogService;

    //初階培訓課程
    private int m_NodeId = 36;

    private int m_Mode
    {
        get { if (ViewState["mode"] == null) { ViewState["mode"] = 0; } return int.Parse(ViewState["mode"].ToString()); }
        set { ViewState["mode"] = value; }
    }

    private string m_PicFileName
    {
        get { if (ViewState["picfilename"] == null) { ViewState["picfilename"] = string.Empty; } return ViewState["picfilename"].ToString(); }
        set { ViewState["picfilename"] = value; }
    }

    private string m_DocFileName
    {
        get { if (ViewState["docfilename"] == null) { ViewState["docfilename"] = string.Empty; } return ViewState["docfilename"].ToString(); }
        set { ViewState["docfilename"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        m_WebLogService = new WebLogService();
        m_PostFactory = new PostFactory();
        m_PostService = m_PostFactory.GetPostService();
        m_QuestionService = m_PostFactory.GetQuestionService();

        if (!IsPostBack)
        {
            pnlContent.Visible = false;
            UpdatePanelSub.Visible = false;
            fillGridView();
            ShowMode();

        }
    }

    private void ShowMode()
    {
        if (m_Mode == 0)
        {
            btnAdd.Visible = true;
            btnSave.Visible = false;
        }
        else
        {
            btnAdd.Visible = false;
            btnSave.Visible = true;
        }
    }

    private void fillGridView()
    {
        //搜尋條件
        //DateTime? startDate = ConvertUtil.ToDateTimeMin(DateTime.Now);

        DateTime? startDate = null;
        string sortField = "SortNo";
        bool sortDesc = false;

        //分頁
        AspNetPager1.RecordCount = m_PostService.CountPostListByNodeId(m_NodeId, false, startDate);
        int pageIndex = (AspNetPager1.CurrentPageIndex - 1);
        int pageSize = AspNetPager1.PageSize;

        gvList.DataSource = m_PostService.GetPostListByNodeId(m_NodeId, false, startDate, pageIndex, pageSize, sortField, sortDesc);
        gvList.DataBind();
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        fillGridView();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        PostVO postVO = new PostVO();
        postVO.Title = txtTitle.Text.Trim();
        postVO.SortNo = int.Parse(txtSortNo.Text.Trim());
        postVO.Node = m_PostService.GetNodeById(m_NodeId);
        //postVO.HtmlContent = ckeContent.value;
        postVO.PicFileName = m_PicFileName;
        postVO.DocFileName = m_DocFileName;
        postVO.Flag = int.Parse(ddlFlag.SelectedValue);
        postVO.Type = int.Parse(ddlType.SelectedValue);  
        WebLogService.SetCreateInfo(postVO);
        m_PostService.CreatePost(postVO);
        m_WebLogService.AddSystemLog(MsgVO.Action.新增, postVO);
        //ClearUI();
        LoadData(postVO);
        fillGridView();        
    }

    private void ClearUI()
    {
        m_Mode = 0;
        m_PicFileName = string.Empty;
        m_DocFileName = string.Empty;
        ltlFile.Text = string.Empty;
        txtTitle.Text = string.Empty;
        txtSortNo.Text = string.Empty;
        //ckeContent.value = string.Empty;
        ddlFlag.SelectedValue = string.Empty;
        ddlType.SelectedValue = string.Empty;
        pnlContent.Visible = false;
        btnShowAdd.Enabled = true;
        UpdatePanelSub.Visible = false;
    }

    private string GetFile(string fileName)
    {
        return string.Format("<br/><a href='../../upload/{0}' target='_blank'>{0}</a>", fileName);
    }

    protected void gvList_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        string cmdName = e.CommandName;
        int postId = int.Parse(e.CommandArgument.ToString());
        PostVO postVO = m_PostService.GetPostById(postId);
        switch (cmdName)
        {
            case "myModify":
                LoadData(postVO);
                break;
            case "myDel":
                ////刪除相關的Question
                IDictionary<string, string> conditions = new Dictionary<string, string>();
                conditions.Add("PostId", postId.ToString());
                IList<QuestionVO> questionList = m_QuestionService.GetQuestionList(conditions);
                if (questionList != null && questionList.Count > 0)
                {
                    foreach (QuestionVO questionVO in questionList)
                    {
                        m_QuestionService.DeleteQuestion(questionVO);
                    }
                }
                m_PostService.DeletePost(postVO);
                m_WebLogService.AddSystemLog(MsgVO.Action.刪除, postVO);
                break;

            default:
                break;
        }
        fillGridView();
    }

    private void LoadData(PostVO postVO)
    {
        ClearUI();
        m_Mode = postVO.PostId;
        m_PicFileName = postVO.PicFileName;
        m_DocFileName = postVO.DocFileName;
        ltlFile.Text = GetFile(m_PicFileName);
        ltlFile2.Text = GetFile(m_DocFileName);
        txtTitle.Text = postVO.Title;
        txtSortNo.Text = postVO.SortNo.ToString();
        //ckeContent.value = postVO.HtmlContent;
        ddlFlag.SelectedValue = postVO.Flag.ToString();
        ddlType.SelectedValue = postVO.Type.ToString();
        ShowMode();
        pnlContent.Visible = true;
        UpdatePanelSub.Visible = true;
        LoadSubList();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearUI();
        ShowMode();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            PostVO postVO = m_PostService.GetPostById(m_Mode);
            postVO.Title = txtTitle.Text.Trim();
            postVO.SortNo = int.Parse(txtSortNo.Text.Trim());
            postVO.Node = m_PostService.GetNodeById(m_NodeId);
            //postVO.HtmlContent = ckeContent.value;
            postVO.PicFileName = m_PicFileName;
            postVO.DocFileName = m_DocFileName;
            postVO.Flag = int.Parse(ddlFlag.SelectedValue);
            postVO.Type = int.Parse(ddlType.SelectedValue);  
            WebLogService.SetUpdateInfo(postVO);
            m_PostService.UpdatePost(postVO);
            m_WebLogService.AddSystemLog(MsgVO.Action.修改, postVO);
            fillGridView();
            ClearUI();
            ShowMode();
        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
            lblMsg.Text = ex.ToString();
        }
    }

    protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //GridView gv = (GridView)sender;
        //if (e.Row.RowIndex != -1)
        //{
        //    Control ctrl = e.Row;
        //    int postId = int.Parse(UIHelper.FindHiddenValue(ref ctrl, "hdnPostId"));
        //    PostVO postVO = m_PostService.GetPostById(postId);
        //}
    }

    protected void btnShowAdd_Click(object sender, EventArgs e)
    {
        ClearUI();
        m_PicFileName = string.Empty;
        m_DocFileName = string.Empty;
        ShowMode();
        pnlContent.Visible = true;
        btnShowAdd.Enabled = false;
    }

    protected void ddlSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        fillGridView();
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                if (i == 0)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetFileName(hpf.FileName);
                        hpf.SaveAs(Server.MapPath("~\\") + "\\upload\\" + fileName);
                        ltlFile.Text = GetFile(fileName);
                        m_PicFileName = fileName;
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("請點選您要上傳的影片!"), false);
                        return;
                    }
                }
            }
        }
        catch
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("影片傳輸錯誤!"), false);
            return;
        }
    }

    protected void btnUpload2_Click(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                if (i == 1)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetFileName(hpf.FileName);
                        hpf.SaveAs(Server.MapPath("~\\") + "\\upload\\" + fileName);
                        ltlFile2.Text = GetFile(fileName);
                        m_DocFileName = fileName;
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("請點選您要上傳的講義!"), false);
                        return;
                    }
                }
            }
        }
        catch
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("講義傳輸錯誤!"), false);
            return;
        }
    }

    protected void btnAddQuestion_Click(object sender, EventArgs e)
    {
        QuestionVO questionVO = new QuestionVO();
        questionVO.Post = m_PostService.GetPostById(m_Mode);
        UIHelper.FillVO(PanelSub, questionVO);
        questionVO.Flag = 1;
        questionVO.CanScore = 5;
        switch (ddlRightAnswer.SelectedValue)
        {
            case "1":
                questionVO.CorrectAnswer = questionVO.Option1;
                break;
            case "2":
                questionVO.CorrectAnswer = questionVO.Option2;
                break;
            case "3":
                questionVO.CorrectAnswer = questionVO.Option3;
                break;
            case "4":
                questionVO.CorrectAnswer = questionVO.Option4;
                break;
        }
        WebLogService.SetCreateInfo(questionVO);
        m_QuestionService.CreateQuestion(questionVO);
        m_WebLogService.AddSystemLog(MsgVO.Action.新增, questionVO);
        LoadSubList();
        UIHelper.ClearUI(PanelSub);
        ddlRightAnswer.SelectedValue = string.Empty;
    }

    private void LoadSubList()
    {
        Dictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("PostId", m_Mode.ToString());
        conditions.Add("Flag", "1");
        conditions.Add("Order", "order by q.CreatedDate desc ");

        //分頁
        AspNetPager2.RecordCount = m_QuestionService.GetQuestionCount(conditions);
        int pageIndex = (AspNetPager2.CurrentPageIndex - 1);
        int pageSize = AspNetPager2.PageSize;
        conditions.Add("PageIndex", pageIndex.ToString());
        conditions.Add("PageSize", pageSize.ToString());

        gvSubList.DataSource = m_QuestionService.GetQuestionList(conditions);
        gvSubList.DataBind();
    }

    protected void AspNetPager2_PageChanged(object sender, EventArgs e)
    {
        LoadSubList();
    }

    protected void gvSubList_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        string cmdName = e.CommandName;
        int questionId = int.Parse(e.CommandArgument.ToString());
        QuestionVO questionVO = m_QuestionService.GetQuestionById(questionId);
        switch (cmdName)
        {
            case "myDel":
                m_QuestionService.DeleteQuestion(questionVO);
                m_WebLogService.AddSystemLog(MsgVO.Action.刪除, questionVO);
                break;

            default:
                break;
        }
        LoadSubList();
    }
}